﻿

Public Class FrmVentas

    
    Dim controller As New Class_RC_Controller.rc_Facturas
    Dim clientes As New Class_RC_Controller.rc_Clientes
    Dim mante As New Class_RC_Controller.rc_Mantenimiento
    Dim productos As New Class_RC_Controller.rc_Productos
    Dim servicios As New Class_RC_Controller.rc_Servicios
    Dim notas As New Class_RC_Controller.rc_Notas

    Private _codNota As Integer = 0

    Public Property codNota() As Integer
        Get
            Return _codNota
        End Get
        Set(value As Integer)
            _codNota = value
        End Set
    End Property

    Private _codFactura As Integer = 0

    Public Property codVenta() As Integer
        Get
            Return _codFactura
        End Get
        Set(value As Integer)
            _codFactura = value
            txtcodigo.Text = value.ToString().PadLeft(4, "0")
        End Set
    End Property

    Private totalfactura As Decimal

    Private Sub llenarCombos()

        Me.cboTipo.SelectedIndex = 1
        Me.cboEstado.SelectedIndex = 1
        Me.cboIVA.SelectedIndex = 2
        Me.cboIvaServicio.SelectedIndex = 2

        Dim ds As DataTable
        ds = clientes.get_Clientes_All(oiml.dbConn, 0, "", "", 0, 0)
        With Me.cboCliente
            .DataSource = ds
            .DisplayMember = "nombre"
            .ValueMember = "codCliente"
        End With

        If IsNumeric(cboCliente.SelectedValue) Then
            CargarClientes_ByID(cboCliente.SelectedValue)
        End If

        Dim dsVend As DataTable
        dsVend = clientes.get_vendedores(oiml.dbConn)
        With Me.cboVendedor
            .DataSource = dsVend
            .DisplayMember = "usuario"
            .ValueMember = "codUsuario"
        End With

        Dim dsTipo As DataTable
        dsTipo = productos.get_tipo_Productos(oiml.dbConn)
        With Me.cboTipoProducto
            .DataSource = dsTipo
            .DisplayMember = "descTipoProducto"
            .ValueMember = "codTipoProducto"
        End With

        CargarProductos()

        Dim dsTipoSer As DataTable
        dsTipoSer = productos.get_tipo_Servicios(oiml.dbConn)
        With Me.cboTipoServicio
            .DataSource = dsTipoSer
            .DisplayMember = "descTipoServicio"
            .ValueMember = "codTipoServicio"
        End With

    End Sub

    Private Sub CargarServicios_ByID(codServicio As Integer, conDescto As Boolean)

        Dim dt As New DataTable
        dt = servicios.get_Servicios_All(oiml.dbConn, codServicio, "", 0, True)

        If Not dt Is Nothing Then

            If IsNumeric(dt.Rows(0)("Precio").ToString()) Then
                txtPrecioServicio.Text = Decimal.Parse(dt.Rows(0)("Precio").ToString())

                If conDescto Then
                    CargarClientes_ByID(cboCliente.SelectedValue)
                End If

            Else
                txtPrecioServicio.Text = 0

            End If

        Else
            txtPrecioServicio.Text = 0

        End If

    End Sub

    Private Sub CargarServicios()

        Dim codTipoServicio As Integer = 0

        If cbxTipoServicio.Checked And IsNumeric(cboTipoServicio.SelectedValue) Then
            codTipoServicio = cboTipoServicio.SelectedValue
        End If

        Dim dt As New DataTable
        dt = servicios.get_Servicios_All(oiml.dbConn, 0, txtServicio.Text, codTipoServicio, True)
        If Not dt Is Nothing Then

            With Me.cboServicio
                .DataSource = dt
                .DisplayMember = "descripcion"
                .ValueMember = "codServicio"
            End With

            SeleccionarServicio(True)

        Else

            cboServicio.DataSource = Nothing
            txtPrecioServicio.Text = 0

        End If

    End Sub

    Private Sub CargarProductos()

        Dim codTipoProducto As Integer = 0

        If cbxTipo.Checked And IsNumeric(cboTipoProducto.SelectedValue) Then
            codTipoProducto = cboTipoProducto.SelectedValue

            Dim dt As New DataTable
            dt = productos.get_Productos_All(oiml.dbConn, 0, txtProducto.Text, codTipoProducto, True)
            If Not dt Is Nothing Then

                With Me.cboProducto
                    .DataSource = dt
                    .DisplayMember = "DescProducto"
                    .ValueMember = "codProducto"
                End With

                SeleccionarProducto(True)

            Else
                cboProducto.DataSource = Nothing
            End If

        End If

    End Sub

    Private Sub CargarClientes_ByID(ByVal codCliente As Integer)

        Dim dt As New DataTable
        dt = clientes.get_Clientes_All(oiml.dbConn, codCliente, "", "", 0, 0)

        If Not dt Is Nothing Then

            If IsNumeric(dt.Rows(0)("porcdescuento").ToString()) Then

                If Decimal.Parse(dt.Rows(0)("porcdescuento").ToString()) > 0 Then

                    txtDescto.Text = Decimal.Parse(dt.Rows(0)("porcdescuento").ToString())
                    txtDescto.Text = FormatNumber(txtDescto.Text, 0, , , TriState.True)

                    txtDescServicio.Text = Decimal.Parse(dt.Rows(0)("porcdescuento").ToString())
                    txtDescServicio.Text = FormatNumber(txtDescto.Text, 0, , , TriState.True)

                    If IsNumeric(txtprecio.Text) Then
                        If Decimal.Parse(txtprecio.Text) > 0 Then

                            Dim calculo As Decimal = 0
                            calculo = Decimal.Parse(txtprecio.Text) * Decimal.Parse(txtDescto.Text) / 100
                            calculo = Decimal.Parse(txtprecio.Text) - calculo
                            txtprecio.Text = FormatNumber(calculo, 0, , , TriState.True)

                        End If

                    End If

                    If IsNumeric(txtPrecioServicio.Text) Then
                        If Decimal.Parse(txtPrecioServicio.Text) > 0 Then

                            Dim calculo As Decimal = 0
                            calculo = Decimal.Parse(txtPrecioServicio.Text) * Decimal.Parse(txtDescServicio.Text) / 100
                            calculo = Decimal.Parse(txtPrecioServicio.Text) - calculo
                            txtPrecioServicio.Text = FormatNumber(calculo, 0, , , TriState.True)

                        End If

                    End If

                Else

                    txtDescto.Text = 0
                    txtDescServicio.Text = 0
                    SeleccionarProducto(False)
                    SeleccionarServicio(False)
                End If

            Else

                txtDescto.Text = 0
                txtDescServicio.Text = 0
                SeleccionarProducto(False)
                SeleccionarServicio(False)
            End If

        Else

            txtDescto.Text = 0
            txtDescServicio.Text = 0
            SeleccionarProducto(False)
            SeleccionarServicio(False)
        End If

    End Sub

    Private Sub CargarProductos_ByID(ByVal codProducto As Integer, ByVal conDescto As Boolean)

        Dim dt As New DataTable
        dt = productos.get_Productos_All(oiml.dbConn, codProducto, "", 0, True)

        If Not dt Is Nothing Then

            If IsNumeric(dt.Rows(0)("PrecioVenta").ToString()) Then
                txtprecio.Text = Decimal.Parse(dt.Rows(0)("PrecioVenta").ToString())
                txtprecio.Text = FormatNumber(txtprecio.Text, 0, , , TriState.True)

                If conDescto Then
                    CargarClientes_ByID(cboCliente.SelectedValue)
                End If

            Else
                txtprecio.Text = 0
            End If

        Else
            txtprecio.Text = 0
        End If

    End Sub

    Private Sub CargarDetalles()
        If codVenta > 0 Then

            Dim dt As New DataTable
            dt = controller.get_Ventas_Detalles_All(oiml.dbConn, codVenta, False, False)

            If Not dt Is Nothing Then
                dgvdetalle.DataSource = dt
                cboTipo.Enabled = False
                txtPedido.ReadOnly = True
                btnPedido.Enabled = False
                cboCliente.Enabled = False
            Else
                dgvdetalle.DataSource = Nothing
                cboTipo.Enabled = True
                txtPedido.ReadOnly = False
                btnPedido.Enabled = True
                cboCliente.Enabled = True
            End If

        End If

    End Sub

    Private Sub ControlCampos(ByVal valor As Boolean)
        fechaFactura.Enabled = valor
        cbxVto.Enabled = valor
        cboCliente.Enabled = valor
        cboVendedor.Enabled = valor
        txtPedido.Enabled = valor
        btnPedido.Enabled = valor
        txtProducto.Enabled = valor
        txtcantidad.Enabled = valor
        txtprecio.Enabled = valor
        cboIVA.Enabled = valor
    End Sub

    Private Sub CargarVenta()
        Try
            If codVenta > 0 Then

                Dim ds As New DataTable
                ds = controller.get_Ventas_ByID(oiml.dbConn, codVenta)

                If Not ds Is Nothing Then

                    ' cargar los controles del formulario con los valores de los campos del registro
                    codVenta = ds.Rows(0)("codVenta").ToString
                    Me.nroFactura.Text = ds.Rows(0)("nroFactura").ToString
                    Me.txtNroRemision.Text = ds.Rows(0)("nroRemision").ToString

                    Me.fechaFactura.Value = DateTime.Parse(ds.Rows(0)("fecha").ToString())

                    If ds.Rows(0)("vencimiento_").ToString <> "" Then
                        Me.fechaVto.Value = DateTime.Parse(ds.Rows(0)("vencimiento").ToString())
                    End If

                    Me.cboTipo.Text = ds.Rows(0)("tipoVenta").ToString
                    Me.cboEstado.Text = ds.Rows(0)("estadoVenta").ToString
                    Me.cboVendedor.SelectedValue = ds.Rows(0)("codVendedor").ToString

                    If ds.Rows(0)("totalVenta").ToString <> "" Then
                        Me.txtTotalFactura.Text = Decimal.Parse(ds.Rows(0)("totalVenta").ToString).ToString("N0")
                        txtTotalFactura.Text = FormatNumber(txtTotalFactura.Text, 0, , , TriState.True)
                    Else
                        Me.txtTotalFactura.Text = 0
                    End If

                    If ds.Rows(0)("totalVentaSaldo").ToString <> "" Then
                        Me.txtSaldo.Text = Decimal.Parse(ds.Rows(0)("totalVentaSaldo").ToString).ToString("N0")
                        txtSaldo.Text = FormatNumber(txtSaldo.Text, 0, , , TriState.True)
                    Else
                        txtSaldo.Text = 0
                    End If

                    If ds.Rows(0)("totalVentaIVA").ToString <> "" Then
                        Me.txtIVA.Text = Decimal.Parse(ds.Rows(0)("totalVentaIVA").ToString).ToString("N0")
                        txtIVA.Text = FormatNumber(txtIVA.Text, 0, , , TriState.True)
                    Else
                        txtIVA.Text = 0
                    End If

                    If ds.Rows(0)("impresa").ToString <> "" Then

                        If Boolean.Parse(ds.Rows(0)("impresa").ToString) Then
                            lblImpresa.Visible = True
                            btnImprimir.Enabled = False
                            btnGrabar.Enabled = False
                            btnAgregarDetalle.Enabled = False
                            btnEliminarDetalle.Enabled = False
                            ControlCampos(False)
                        End If

                    Else
                        lblImpresa.Visible = False
                        btnImprimir.Enabled = True
                    End If

                    If ds.Rows(0)("codNota").ToString <> "" Then

                        If ds.Rows(0)("NroNota").ToString <> "" And CInt(ds.Rows(0)("codNota")) > 0 Then
                            txtPedido.Text = ds.Rows(0)("nroNota").ToString
                            txtPedido.ReadOnly = True
                            btnPedido.Enabled = False

                            If Integer.Parse(ds.Rows(0)("codNota").ToString) > 0 Then
                                txtPedido.Text = ds.Rows(0)("nroNota").ToString
                                txtPedido.ReadOnly = True
                                btnPedido.Enabled = False
                            End If
                        Else
                            txtPedido.ReadOnly = False
                            btnPedido.Enabled = True
                        End If
                    End If

                    ControlEstado()

                    Me.cboCliente.SelectedValue = ds.Rows(0)("codCliente").ToString

                    Me.lblUsuario.Text = ds.Rows(0)("usuario").ToString
                    Me.lblfechaActualizacion.Text = ds.Rows(0)("fechaActualizacion_").ToString

                    CargarDetalles()


                End If

            Else

                ' cargar los controles del formulario con los valores de los campos del registro
                codVenta = 0
                Me.nroFactura.Text = ""
                Me.fechaFactura.Value = DateTime.Now
                Me.fechaVto.Value = DateTime.Now

                Me.cboTipo.SelectedIndex = 0
                Me.cboTipoProducto.SelectedIndex = 0
                Me.cboIVA.SelectedIndex = 0
                Me.cboEstado.SelectedIndex = 0

                Me.txtTotalFactura.Text = 0
                Me.txtSaldo.Text = 0
                Me.txtIVA.Text = 0

                Me.cboCliente.SelectedIndex = 0

                lblUsuario.Text = oiml.Usuario
                lblfechaActualizacion.Text = Date.Now.ToShortDateString

                fechaFactura.Focus()

            End If

            'Me.ControlPermisos()

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub ControlEstado()
        If Me.cboEstado.Text = "APROBADA" Then
            grbCabecera.Enabled = False
            grbDetalle.Enabled = False
        ElseIf Me.cboEstado.Text = "ANULADA" Then
            grbCabecera.Enabled = False
            grbDetalle.Enabled = False
            btnGrabar.Enabled = False
            btnAnular.Enabled = False
            btnImprimir.Enabled = False
            btnRemision.Enabled = False
            btnAgregarDetalle.Enabled = False
            btnEliminarDetalle.Enabled = False
            btnImprimirRemision.Enabled = False
        Else

            If Me.txtNroRemision.Text <> "" Then
                btnRemision.Enabled = False
                btnImprimirRemision.Enabled = True
                btnGrabar.Enabled = False
                btnAgregarDetalle.Enabled = False
                btnEliminarDetalle.Enabled = False
            Else
                btnRemision.Enabled = True
                btnImprimirRemision.Enabled = False
            End If

            If Me.nroFactura.Text <> "" Then
                btnImprimir.Enabled = True
                'btnRemision.Enabled = True
                btnAnular.Enabled = True
                btnEliminar.Enabled = False
            Else
                btnImprimir.Enabled = False
                btnRemision.Enabled = False
                btnAnular.Enabled = False
                btnEliminar.Enabled = True
            End If

            'Se comenta el control de totales es por el detalle al inser o delete
            'If controller.Update_Ventas(oiml.dbConn, codVenta, nroFactura.Text, fechaFactura.Value, "", cboTipo.Text, cboEstado.Text,
            '                            Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboCliente.SelectedValue,
            '                            cboVendedor.SelectedValue, oiml.idUsuario, False, txtDescto.Text) = False Then
            '    MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)
            '    Exit Sub
            'End If

        End If
    End Sub

    Private Shadows Sub KeyUpmask(ByVal MaskedTextboxs As System.Windows.Forms.MaskedTextBox, ByVal e As System.Windows.Forms.KeyEventArgs)

        'Teclas que Utilizaremos El cual solo son las numericas
        If e.KeyData = Keys.Space Or e.KeyData = Keys.Decimal Or _
         e.KeyData = Keys.NumPad0 Or e.KeyData = Keys.NumPad1 Or e.KeyData = Keys.NumPad2 Or e.KeyData = Keys.NumPad3 _
           Or e.KeyData = Keys.NumPad4 Or e.KeyData = Keys.NumPad5 Or e.KeyData = Keys.NumPad6 Or _
           e.KeyData = Keys.NumPad7 Or e.KeyData = Keys.NumPad8 Or e.KeyData = Keys.NumPad9 _
           Or e.KeyData = Keys.D0 Or e.KeyData = Keys.D1 Or e.KeyData = Keys.D2 Or e.KeyData = Keys.D3 Or _
           e.KeyData = Keys.D4 Or e.KeyData = Keys.D5 Or e.KeyData = Keys.D6 _
           Or e.KeyData = Keys.D7 Or e.KeyData = Keys.D8 Or e.KeyData = Keys.D9 Or e.KeyData = Keys.Tab Or e.KeyData = Keys.Enter _
            Then

            'Programamos la tecla de Retroceso en el textbox
        ElseIf e.KeyData = Keys.Back And MaskedTextboxs.Text.Length > 0 Then
            On Error Resume Next
            'Removemos un caracter mediante se presione la tecla Back
            MaskedTextboxs.Text.Remove(MaskedTextboxs.SelectionStart - 1)

            'si el textbox es menor que un caracter
        ElseIf MaskedTextboxs.Text.Length < 1 Then
            'ponemos el textbox En Blanco
            MaskedTextboxs.Text = String.Empty
            'ponemos la variable    NumerosYaescritos en Blanco

        Else
            'ponemos el textbox enblanco
            MaskedTextboxs.Text = String.Empty
            'Hacemos Sonar un Beep para indicarle al usuario que ha presionado un caracter y no un Numero
            Beep()
            MsgBox("Introducir solo valores numericos")
        End If

    End Sub

    Private Shadows Sub KeyUp(ByVal TextBoxs As System.Windows.Forms.TextBox, ByVal e As System.Windows.Forms.KeyEventArgs)

        'Teclas que Utilizaremos El cual solo son las numericas
        If e.KeyData = Keys.Space Or e.KeyData = Keys.Decimal Or _
         e.KeyData = Keys.NumPad0 Or e.KeyData = Keys.NumPad1 Or e.KeyData = Keys.NumPad2 Or e.KeyData = Keys.NumPad3 _
           Or e.KeyData = Keys.NumPad4 Or e.KeyData = Keys.NumPad5 Or e.KeyData = Keys.NumPad6 Or _
           e.KeyData = Keys.NumPad7 Or e.KeyData = Keys.NumPad8 Or e.KeyData = Keys.NumPad9 _
           Or e.KeyData = Keys.D0 Or e.KeyData = Keys.D1 Or e.KeyData = Keys.D2 Or e.KeyData = Keys.D3 Or _
           e.KeyData = Keys.D4 Or e.KeyData = Keys.D5 Or e.KeyData = Keys.D6 _
           Or e.KeyData = Keys.D7 Or e.KeyData = Keys.D8 Or e.KeyData = Keys.D9 Or e.KeyData = Keys.Tab Or e.KeyData = Keys.Enter _
           Or e.KeyData = Keys.OemMinus Then

            'Programamos la tecla de Retroceso en el textbox
        ElseIf e.KeyData = Keys.Back And TextBoxs.Text.Length > 0 Then
            On Error Resume Next
            'Removemos un caracter mediante se presione la tecla Back
            TextBoxs.Text.Remove(TextBoxs.SelectionStart - 1)

            'si el textbox es menor que un caracter
        ElseIf TextBoxs.Text.Length < 1 Then
            'ponemos el textbox En Blanco
            TextBoxs.Text = String.Empty
            'ponemos la variable    NumerosYaescritos en Blanco

        Else
            'ponemos el textbox enblanco
            TextBoxs.Text = String.Empty
            'Hacemos Sonar un Beep para indicarle al usuario que ha presionado un caracter y no un Numero
            Beep()
            MsgBox("Introducir solo valores numericos")
        End If

    End Sub

    Private Sub FrmVentas_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
        'If nroFactura.Text = "" Then
        '    controller.Delete_Ventas(oiml.dbConn, codVenta, oiml.idUsuario)
        'End If

    End Sub

    

    Private Sub FrmVentas_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.dgvdetalle.AutoGenerateColumns = False
        Me.llenarCombos()
        Me.CargarVenta()

    End Sub

    Private Sub ControlPermisos()

        If Not oiml.ControlPermiso(oiml.idUsuario, "ACTUALIZAR VENTAS") Then
            Me.btnGrabar.Enabled = False
        End If

        If Not oiml.ControlPermiso(oiml.idUsuario, "ANULAR VENTAS") Then
            Me.btnAnular.Enabled = False
        End If

        If Not oiml.ControlPermiso(oiml.idUsuario, "BORRAR VENTAS") Then
            Me.btnEliminar.Enabled = False
        End If

        If Not oiml.ControlPermiso(oiml.idUsuario, "IMPRIMIR FACTURA") Then
            Me.btnImprimir.Enabled = False
        End If

        If Not oiml.ControlPermiso(oiml.idUsuario, "REGISTRAR REMISION") Then
            Me.btnRemision.Enabled = False
        End If

        If Not oiml.ControlPermiso(oiml.idUsuario, "IMPRIMIR REMISION") Then
            Me.btnImprimirRemision.Enabled = False
        End If

        If Not oiml.ControlPermiso(oiml.idUsuario, "FACTURAR PEDIDOS") Then
            Me.btnPedido.Enabled = False
            Me.txtPedido.Enabled = False
        End If
        If Not oiml.ControlPermiso(oiml.idUsuario, "RE IMPRESION DE FACTURA") Then
            Me.btnImprimir.Enabled = False
        End If
    End Sub

    Private Function ValidarCampos() As Boolean

        Dim controlCampos As Boolean = False

        'If nroFactura.Text = "" Then
        '    ErrorProvider.SetError(nroFactura, "Campo obligatorio")
        '    controlCampos = True
        'Else
        '    ErrorProvider.SetError(nroFactura, "")
        'End If

        If fechaFactura.Value.ToString = "" Then
            ErrorProvider.SetError(fechaFactura, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider.SetError(fechaFactura, "")
        End If
        '
        Return controlCampos

    End Function

    Private Function ValidarDetallesCampos() As Boolean

        Dim controlCampos As Boolean = False

        If Not IsNumeric(txtcantidad.Text) Then
            'ErrorProvider.SetError(txtcantidad, "Campo numerico, cantidad")
            'controlCampos = True
            txtcantidad.Text = 1
        Else
            ErrorProvider.SetError(txtcantidad, "")
        End If        '

        If Not IsNumeric(txtprecio.Text) Then
            'ErrorProvider.SetError(txtprecio, "Campo numerico, cantidad")
            'controlCampos = True
            txtprecio.Text = 0
        Else
            ErrorProvider.SetError(txtprecio, "")
        End If        '

        Return controlCampos

    End Function

    Private Sub btncancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelar.Click
        Me.Close()
    End Sub

    Private Sub btnAgregarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregarDetalle.Click
        Try

            Dim fechaVtoValor As String = ""
            If cbxVto.Checked Then
                fechaVto.Value = fechaVto.Value.AddDays(30)
                fechaVtoValor = fechaVto.Value.ToString
            End If

            txtcantidad_Leave(sender, e)
            txtCantidadServicio_Leave(sender, e)

            If TabControl1.SelectedIndex = 0 And ValidarDetallesCampos() Then

                MessageBox.Show("Falta llenar datos del detalle", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
                txtcantidad.Focus()

            ElseIf TabControl1.SelectedIndex = 1 And ValidarDetallesServicios() Then

                MessageBox.Show("Falta llenar datos del detalle", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
                txtCantidadServicio.Focus()

            Else

                If codVenta = 0 Then

                    If ValidarCampos() Then
                        nroFactura.Focus()
                        Exit Sub
                    Else
                        
                        codVenta = controller.Insert_Ventas(oiml.dbConn, nroFactura.Text, fechaFactura.Value, fechaVtoValor, cboTipo.Text, cboEstado.Text,
                                        Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboCliente.SelectedValue,
                                        cboVendedor.SelectedValue, oiml.idUsuario, False, codNota, txtDescto.Text)

                        If codVenta = 0 Then
                            MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            Exit Sub
                        End If

                    End If

                Else

                    If ValidarCampos() Then
                        nroFactura.Focus()
                        Exit Sub
                    Else

                        If controller.Update_Ventas(oiml.dbConn, codVenta, nroFactura.Text, fechaFactura.Value, fechaVtoValor, cboTipo.Text, cboEstado.Text,
                                        Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboCliente.SelectedValue,
                                        cboVendedor.SelectedValue, oiml.idUsuario, False, txtDescto.Text) = False Then
                            MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            Exit Sub
                        End If

                    End If

                End If

                Dim ivaMonto As Decimal = 0
                Dim iva As Decimal = 0
                Dim total As Decimal = Decimal.Parse(txttotal.Text)

                If cboIVA.Text.ToString = "05%" Then
                    ivaMonto = total / 21
                    iva = 5
                ElseIf cboIVA.Text.ToString = "10%" Then
                    ivaMonto = total / 11
                    iva = 10
                End If

                If codVenta > 0 Then

                    If TabControl1.SelectedTab.Name = "TabProductos" Then

                        If controller.Insert_Ventas_Detalle(oiml.dbConn, codVenta, cboProducto.SelectedValue, Decimal.Parse(txtcantidad.Text),
                                                        Decimal.Parse(txtprecio.Text), iva,
                                                        ivaMonto, Decimal.Parse(txttotal.Text),
                                                        cboCliente.SelectedValue, cboTipo.Text, oiml.idUsuario, 0) Then
                            CargarVenta()
                            limpiarDetalles()
                            'totales()
                        Else
                            MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)

                        End If

                    ElseIf TabControl1.SelectedTab.Name = "TabServicios" Then

                        If controller.Insert_Ventas_Detalle(oiml.dbConn, codVenta, 0, Decimal.Parse(txtCantidadServicio.Text),
                                                        Decimal.Parse(txtPrecioServicio.Text), iva,
                                                        ivaMonto, Decimal.Parse(txtTotalServicio.Text),
                                                        cboCliente.SelectedValue, cboTipo.Text, oiml.idUsuario, cboServicio.SelectedValue) Then
                            CargarVenta()
                            limpiarDetallesServicios()
                            'totales()
                        Else
                            MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)

                        End If

                    End If



                End If

            End If

        Catch ex As Exception
            MsgBox(ex.Message)

        End Try

        txtcantidad.Text = 1
        txtCantidadServicio.Text = 1

    End Sub

    Private Function btnAgregarDetalle_Click(ByVal ivaText As String, ByVal total As Decimal,
                                             ByVal codProducto As Integer, ByVal cantidad As Decimal,
                                             ByVal precio As Decimal, codServicio As Integer) As Boolean
        Try
            Dim fechaVtoValor As String = ""
            If cbxVto.Checked Then
                fechaVtoValor = fechaVto.Value.ToString
            End If

            If codVenta = 0 Then

                If ValidarCampos() Then
                    nroFactura.Focus()
                    Return False
                Else

                    codVenta = controller.Insert_Ventas(oiml.dbConn, nroFactura.Text, fechaFactura.Value, fechaVtoValor, cboTipo.Text, cboEstado.Text,
                                    Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboCliente.SelectedValue,
                                    cboVendedor.SelectedValue, oiml.idUsuario, True, codNota, txtDescto.Text)

                    If codVenta = 0 Then
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        Return False
                    End If

                End If

            Else

                If ValidarCampos() Then
                    nroFactura.Focus()
                    Return False
                Else

                    If controller.Update_Ventas(oiml.dbConn, codVenta, nroFactura.Text, fechaFactura.Value, fechaVtoValor, cboTipo.Text, cboEstado.Text,
                                    Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboCliente.SelectedValue,
                                    cboVendedor.SelectedValue, oiml.idUsuario, False, txtDescto.Text) = False Then
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        Return False
                    End If

                End If

            End If

            Dim ivaMonto As Decimal = 0
            Dim iva As Decimal = 0
            'Dim total As Decimal = Decimal.Parse(txttotal.Text)

            If ivaText = "05%" Then
                ivaMonto = total / 21
                iva = 5
            ElseIf ivaText = "10%" Then
                ivaMonto = total / 11
                iva = 10
            End If

            If codVenta > 0 Then
                If controller.Insert_Ventas_Detalle(oiml.dbConn, codVenta, codProducto, cantidad,
                                                    precio, iva, ivaMonto, total, cboCliente.SelectedValue,
                                                    cboTipo.Text, oiml.idUsuario, codServicio) Then
                    Return True

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Return False
                End If

            End If

        Catch ex As Exception
            MsgBox(ex.Message)
            Return False
        End Try

    End Function

    Public Sub limpiarDetalles()
        txtcantidad.Text = 1
        'txtprecio.Text = 0
        'txttotal.Text = 0
        txtProducto.Text = ""
        SeleccionarProducto(True)

    End Sub

    Public Sub limpiarDetallesServicios()
        txtCantidadServicio.Text = 1
        'txtprecio.Text = 0
        'txttotal.Text = 0
        txtServicio.Text = ""
        SeleccionarServicio(True)

    End Sub

    'Private Sub totales()
    '    Dim i As Integer
    '    totalfactura = 0

    '    For i = 0 To dgvdetalle.Rows.Count - 1
    '        totalfactura += CDec(dgvdetalle.Rows(i).Cells(6).Value)
    '    Next

    '    txtTotalFactura.Text = FormatNumber(totalfactura, 0, , , TriState.True)

    '    If cboTipo.Text = "CREDITO" Then
    '        txtSaldo.Text = FormatNumber(totalfactura, 0, , , TriState.True)
    '    Else
    '        txtSaldo.Text = 0
    '    End If


    'End Sub

    Private Sub btnEliminarDetalle_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminarDetalle.Click
        Try
            If dgvdetalle.SelectedRows.Count > 0 Then
                Dim codDetalle As Integer
                Dim codDetalleServicio As Integer

                codDetalle = dgvdetalle.SelectedRows(0).Cells(0).Value
                codDetalleServicio = dgvdetalle.SelectedRows(0).Cells(2).Value

                If (codDetalle > 0 Or codDetalleServicio > 0) And MessageBox.Show("Desea eliminar el registro seleccionado?", "Ventas", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                    If controller.Delete_Ventas_Detalle(oiml.dbConn, codVenta, codDetalle, oiml.idUsuario, codDetalleServicio) Then
                        CargarVenta()
                        dgvdetalle.Refresh()
                        'totales()
                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If

            End If

        Catch ex As Exception
            MsgBox(ex.Message)

        End Try

    End Sub

    Private Sub btnGrabar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrabar.Click

        If nroFactura.Text = "" Then
            If MessageBox.Show("Desea confirmar la operacion de venta factura?", "Ventas", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
                Return
            End If
        End If

        If ValidarCampos() Then
            nroFactura.Focus()
            Exit Sub
        End If

        Dim fechaVtoValor As String = ""
        If cbxVto.Checked Then
            fechaVtoValor = fechaVto.Value.ToString
        End If

        If codVenta = 0 Then

            codVenta = controller.Insert_Ventas(oiml.dbConn, nroFactura.Text, fechaFactura.Value, fechaVtoValor, cboTipo.Text, cboEstado.Text,
                                        Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboCliente.SelectedValue,
                                        cboVendedor.SelectedValue, oiml.idUsuario, True, codNota, txtDescto.Text)

            If codVenta > 0 Then

                oiml.Log(oiml.idUsuario, "Registro de venta, codigo: " & codVenta, 1, Nothing)
                MessageBox.Show("Registro grabado con exito!", "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Me.DialogResult = Windows.Forms.DialogResult.OK
                CargarVenta()

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        Else
            If controller.Update_Ventas(oiml.dbConn, codVenta, nroFactura.Text, fechaFactura.Value, fechaVtoValor, cboTipo.Text, cboEstado.Text,
                                        Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboCliente.SelectedValue,
                                        cboVendedor.SelectedValue, oiml.idUsuario, True, txtDescto.Text) Then

                MessageBox.Show("Registro grabado con exito!", "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Me.DialogResult = Windows.Forms.DialogResult.OK
                CargarVenta()

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

    End Sub

    Private Sub btneliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEliminar.Click

        Try
            If codVenta > 0 Then
                If MessageBox.Show("Desea eliminar el registro seleccionado?", "Ventas", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                    If controller.Delete_Ventas(oiml.dbConn, codVenta, oiml.idUsuario) Then
                        Me.Close()

                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If
            End If


        Catch ex As Exception
            MsgBox(ex.Message)

        End Try

    End Sub

    Private Sub txtprecio_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtprecio.Leave

        If ValidarDetallesCampos() Then
            txtprecio.Focus()
        Else
            txttotal.Text = Decimal.Parse(txtcantidad.Text) * Decimal.Parse(txtprecio.Text)
            txttotal.Text = FormatNumber(txttotal.Text, 0, , , TriState.True)
        End If

    End Sub

    Private Sub txtcantidad_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtcantidad.Leave

        If ValidarDetallesCampos() Then
            txtcantidad.Focus()
        Else
            txttotal.Text = Decimal.Parse(txtcantidad.Text) * Decimal.Parse(txtprecio.Text)
            txttotal.Text = FormatNumber(txttotal.Text, 0, , , TriState.True)
        End If

    End Sub

    Private Sub cbxTipo_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxTipo.CheckedChanged
        CargarProductos()
    End Sub

    Private Sub cboTipoProducto_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cboTipoProducto.KeyDown
        If e.KeyCode = Keys.Enter Then
            CargarProductos()
        End If
    End Sub

    Private Sub txtProducto_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtProducto.KeyDown
        If e.KeyCode = Keys.Enter Then
            CargarProductos()
        End If
    End Sub

    Private Sub cboProducto_SelectedpValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboProducto.SelectedValueChanged

        SeleccionarProducto(True)

    End Sub

    Private Sub SeleccionarProducto(ByVal conDescto As Boolean)
        If Not cboProducto.SelectedValue Is Nothing Then
            If cboProducto.SelectedValue.ToString <> "System.Data.DataRowView" Then
                CargarProductos_ByID(cboProducto.SelectedValue, conDescto)
            End If
        End If

    End Sub

    Private Sub SeleccionarServicio(ByVal conDescto As Boolean)
        If Not cboServicio.SelectedValue Is Nothing Then
            If cboServicio.SelectedValue.ToString <> "System.Data.DataRowView" Then
                CargarServicios_ByID(cboServicio.SelectedValue, conDescto)
            End If
        End If

    End Sub

    Private Sub cbxVto_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxVto.CheckedChanged
        fechaVto.Enabled = cbxVto.Checked
    End Sub

    Private Sub cboTipoProducto_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboTipoProducto.SelectedValueChanged

        CargarProductos()

    End Sub

    Private m_frmRpts As FormReportes
    Public Property frmRpts() As FormReportes
        Get
            Return m_frmRpts
        End Get
        Set(ByVal value As FormReportes)
            m_frmRpts = value
        End Set
    End Property

    Private Sub btnImprimir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImprimir.Click
        If codVenta > 0 Then
            If MessageBox.Show("Desea confirmar e imprimir el registro seleccionado?", "Ventas", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                Dim dt As New DataTable
                dt = controller.get_Ventas_Producto_ByID(oiml.dbConn, codVenta)

                Dim conv As New Conversiones.Conv()

                If frmRpts Is Nothing Then
                    frmRpts = New FormReportes()
                    frmRpts.MontoLetras = "GUARANIES " & conv.enletras(txtTotalFactura.Text, False)
                    frmRpts.tipo_Reporte = "FACTURAS"
                    frmRpts.datos_Reporte = dt
                    frmRpts.ShowDialog()
                Else

                    If Not frmRpts.Visible Then
                        frmRpts = New FormReportes()
                        frmRpts.MontoLetras = "GUARANIES " & conv.enletras(txtTotalFactura.Text, False)
                        frmRpts.tipo_Reporte = "FACTURAS"
                        frmRpts.datos_Reporte = dt
                        frmRpts.ShowDialog()
                    Else
                        frmRpts.MontoLetras = "GUARANIES " & conv.enletras(txtTotalFactura.Text, False)
                        frmRpts.tipo_Reporte = "FACTURAS"
                        frmRpts.datos_Reporte = dt
                        frmRpts.Select()
                        frmRpts.Activate()
                    End If

                End If

                If Not controller.MessageError Is Nothing Then
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Return
                End If

                If controller.Update_Ventas_Impresion(oiml.dbConn, codVenta, oiml.idUsuario) Then
                    Me.Close()

                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Return
                End If

            End If
        End If

    End Sub

    Private Sub btnPedido_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPedido.Click
        Try
            Dim dt As New DataTable
            dt = notas.get_Notas_ByNRO(oiml.dbConn, txtPedido.Text, oiml.codEstadoCierreNota, True)

            If Not dt Is Nothing And dt.Rows.Count > 0 Then
                codNota = dt.Rows(0)("codNota").ToString

                Dim dtDetalle As New DataTable
                dtDetalle = notas.get_Notas_Detalles_All(oiml.dbConn, codNota, False, False, False)

                If Not dt Is Nothing Then

                    'And dt.Rows.Count > 0

                    If MessageBox.Show("Desea facturar el pedido nro. " & txtPedido.Text & "?", "Pedidos", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                        cboCliente.SelectedValue = dt.Rows(0)("codCliente").ToString

                        Dim total As Decimal = 0
                        Dim codProducto As Integer = 0
                        Dim codServicio As Integer = 0
                        Dim ivaCodigo As String = "10%"

                        For i As Integer = 0 To dtDetalle.Rows.Count - 1

                            total = dtDetalle.Rows(i)("cantidad") * dtDetalle.Rows(i)("precio")

                            If dtDetalle.Rows(i)("codProducto").ToString <> "" Then
                                codProducto = dtDetalle.Rows(i)("codProducto")
                            Else
                                codServicio = dtDetalle.Rows(i)("codServicio")
                            End If

                            If dtDetalle.Rows(i)("iva").ToString = "10" Then
                                ivaCodigo = "10%"
                            ElseIf dtDetalle.Rows(i)("iva").ToString = "5" Then
                                ivaCodigo = "05%"
                            Else
                                ivaCodigo = "0%"
                            End If

                            btnAgregarDetalle_Click(ivaCodigo, total, codProducto, dtDetalle.Rows(i)("cantidad"), dtDetalle.Rows(i)("precio"), codServicio)

                        Next

                        grbDetalle.Enabled = False
                        CargarVenta()
                        MessageBox.Show("Registro grabado con exito!", "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

                    End If

                End If

            Else
                MessageBox.Show("Pedido no encontrado, favor verifique su estado Finalizado o si ya no fue facturado.", "Pedidos", MessageBoxButtons.OK, MessageBoxIcon.Information)

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    Private Sub btnAnular_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnular.Click
        Try
            If codVenta > 0 Then
                If MessageBox.Show("Desea anular el registro seleccionado?", "Ventas", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                    If controller.Update_Ventas_Estado(oiml.dbConn, codVenta, "ANULADA", oiml.idUsuario) Then
                        Me.Close()

                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If
            End If


        Catch ex As Exception
            MsgBox(ex.Message)

        End Try
    End Sub

    Private Sub txtPedido_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPedido.KeyDown
        If e.KeyCode = Keys.Enter Then
            btnPedido_Click(sender, e)
        End If
    End Sub

    Private Sub txtcantidad_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtcantidad.TextChanged

    End Sub

    Private Sub cboTipo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboTipo.SelectedIndexChanged
        If cboTipo.Text = "CREDITO" Then
            cboEstado.Text = "EN PROCESO"
            cbxVto.Checked = True
            cbxVto.Enabled = False
        Else
            cboEstado.Text = "PAGADA"
            cbxVto.Checked = False
            cbxVto.Enabled = False
        End If
    End Sub

    Private Sub btnRemision_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemision.Click

        If codVenta > 0 And nroFactura.Text <> "" And txtNroRemision.Text = "" Then
            If MessageBox.Show("Desea generar la remision del registro seleccionado?", "Ventas", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                If controller.Update_Ventas(oiml.dbConn, codVenta, oiml.idUsuario) Then

                    MessageBox.Show("Nota de Remision Generada!", "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    Me.DialogResult = Windows.Forms.DialogResult.OK
                    CargarVenta()
                Else
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)

                End If

            End If
        End If
    End Sub

    Private Sub btnImprimirRemision_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImprimirRemision.Click
        If txtNroRemision.Text <> "" Then
            If MessageBox.Show("Desea confirmar e imprimir el registro seleccionado?", "Remision", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                Dim dt As New DataTable
                dt = controller.get_Ventas_Producto_ByID(oiml.dbConn, codVenta)

                If frmRpts Is Nothing Then
                    frmRpts = New FormReportes()
                    frmRpts.tipo_Reporte = "REMISION"
                    frmRpts.datos_Reporte = dt
                    frmRpts.ShowDialog()
                Else

                    If Not frmRpts.Visible Then
                        frmRpts = New FormReportes()
                        frmRpts.tipo_Reporte = "REMISION"
                        frmRpts.datos_Reporte = dt
                        frmRpts.ShowDialog()
                    Else
                        frmRpts.tipo_Reporte = "REMISION"
                        frmRpts.datos_Reporte = dt
                        frmRpts.Select()
                        frmRpts.Activate()
                    End If

                End If

                If Not controller.MessageError Is Nothing Then
                    MessageBox.Show("Error: " & controller.MessageError.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    Return
                End If

                'If controller.Update_Ventas_Impresion(oiml.dbConn, codVenta, oiml.idUsuario) Then
                'Me.Close()

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Return
            End If

        End If
    End Sub

    Private Sub cboCliente_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboCliente.SelectedValueChanged

        If IsNumeric(cboCliente.SelectedValue) Then
            CargarClientes_ByID(cboCliente.SelectedValue)
        End If

    End Sub


    Private Sub cboTipoServicio_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboTipoServicio.SelectedValueChanged
        CargarServicios()
    End Sub

    Private Sub cboServicio_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboServicio.SelectedValueChanged
        SeleccionarServicio(True)
    End Sub

    Private Sub txtServicio_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtServicio.KeyDown
        If e.KeyCode = Keys.Enter Then
            CargarServicios()
        End If
    End Sub

    Private Function ValidarDetallesServicios() As Boolean

        Dim controlCampos As Boolean = False

        If Not IsNumeric(txtcantidad.Text) Then
            'ErrorProvider.SetError(txtcantidad, "Campo numerico, cantidad")
            'controlCampos = True
            txtcantidad.Text = 1
        Else
            ErrorProvider.SetError(txtcantidad, "")
        End If        '

        If cboServicio.SelectedValue = 0 Then
            ErrorProvider.SetError(cboServicio, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider.SetError(cboServicio, "")
        End If

        Return controlCampos

    End Function

    Private Sub TabControl1_TabIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.TabIndexChanged
        If TabControl1.SelectedIndex = 0 Then
            SeleccionarProducto(True)
        Else
            SeleccionarServicio(True)
        End If
    End Sub

    Private Sub txtCantidadServicio_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCantidadServicio.Leave
        If ValidarDetallesServicios() Then
            txtCantidadServicio.Focus()
        Else
            txtTotalServicio.Text = Decimal.Parse(txtCantidadServicio.Text) * Decimal.Parse(txtPrecioServicio.Text)
            txtTotalServicio.Text = FormatNumber(txtTotalServicio.Text, 0, , , TriState.True)
        End If
    End Sub

  
End Class